package com.edison.controller;

import brave.Tracer;
import com.edison.democommon.api.ApiResponse;
import com.edison.democommon.api.Metadata;
import com.edison.democommon.exception.BadRequestException;
import com.edison.democommon.exception.UnauthorizedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author edison
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Resource
    private Tracer tracer;

    @ExceptionHandler(BadRequestException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<String> handleBadRequestException(BadRequestException ex) {
        return getStringApiResponse(ex.getStatus(), ex.getError(), ex.getMessage());
    }


    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ApiResponse<String> handleUnauthorizedException(UnauthorizedException ex) {
        return getStringApiResponse(ex.getStatus(), ex.getError(), ex.getMessage());
    }

    private ApiResponse<String> getStringApiResponse(int status, String error, String message) {
        String traceId = tracer.currentSpan().context().traceIdString();
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
        Metadata metadata = new Metadata(traceId, timestamp);
        return new ApiResponse<>(status, error, message, null, metadata);
    }

}
